<?php
namespace app\mp\admin;
use app\system\admin\Admin;
use think\Db;
use app\common\service\StallCost as StallCostService;
class StallBill extends Admin
{
	/**
     * 添加费用单
     *
     * @author 飞燕
     * @date 2021年3月17日
     */
	public function makeStallBill(){
		$stallFeedIds = $this->request->param('id', []);
		if (empty($stallFeedIds)) {
			return $this->error('缺少id参数');
		}
		$where[]=['id', 'in' , $stallFeedIds];
		$stList=db('stall_feed')->where($where)->select();
		$stallId=array_unique(array_column($stList,'stall_id'));
		$billmonth= $this->request->param('billmonth', '');
		$pay_type=$this->request->param('pay_type', 1);
		try {
    		db()->startTrans();
            $stallCostService=new StallCostService();
    		foreach ($stallId as $index=>$stallIdval){ //分供应商处理
                $stList=db('stall_feed')->where($where)->where("stall_id",'=',$stallIdval)->select();
                foreach ($stList as $k => $v) {
                    $stList[$k]['billing_caigou_amount'] = floatval($v['billing_caigou_count_feed'])*floatval($v['caigou_unitprice']);
                    $stallCostList=$stallCostService->getListByStallFeedId($v['id']);
                    $stList[$k]['stall_cost_money']=array_sum(array_column($stallCostList,'stall_cost_money'))?array_sum(array_column($stallCostList,'stall_cost_money')):0;
                }
                $amountMoney=floatval(array_sum(array_column($stList,'billing_caigou_amount')));
                $feedMoney=floatval(array_sum(array_column($stList,'stall_cost_money')));
                $billData=[
                    'stall_id'=>$stallIdval,
                    'pay_month'=>$billmonth,
                    'pay_type'=>$pay_type,
                    'amount_money'=> $amountMoney,
                    'feed_money'=>$feedMoney,
                    'actually_money'=>$amountMoney-$feedMoney,
                    'admin_id'=>ADMIN_ID,
                    'create_time'=>time(),
                    'update_time'=>time()
                ];

                $stallBillId=db('stall_bill')->insertGetId($billData);
                db('stall_feed')->where($where)->where("stall_id",'=',$stallIdval)->update(['status'=>3]);
                foreach ($stList as $key => $value) {
                    $stallBillFeedData=[
                        'pay_month'=>$billmonth,
                        'pay_type'=>$pay_type,
                        'stall_bill_id'=>$stallBillId,
                        'stall_feed_id'=>$value['id'],
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    db('stall_bill_feed')->insert($stallBillFeedData);
                }
            }
			db()->commit();
	    	return $this->Json(1);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
	}

}

